package com.auto.learning.service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.auto.learning.R;
import com.auto.learning.bean.AnchorBean;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.DownLoadBean;
import com.auto.learning.bean.ReadModeBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.SelectionVo;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.ProgressEvent;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.Cache;
import com.auto.learning.net.DownLoadInfo;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpHelper;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.store.core.StaticReference;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.FileUtil;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;

public class DownLoadManager3 implements DialogListener{
	
	private final static int GETCACHEDATA_SUCCESS = 1;
	private ArrayList<Integer> bookIds = new ArrayList<Integer>();
	private Context context;
	private int downloadingBookId = 0;
	private boolean needPrepare = false;
	
	public int getDownloadingBookId() {
		return downloadingBookId;
	}

	public void setDownloadingBookId(int downloadingBookId) {
		this.downloadingBookId = downloadingBookId;
	}

	private Handle handler =new Handle(context){
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult result = (ResponeResult)msg.obj;
				ReadModeBean readModeBean = new Gson().fromJson(result.getData(), new TypeToken<ReadModeBean>(){}.getType());
				Cache.cacheReadMode2Local(readModeBean);
				getLocalBookBean(readModeBean.getBookId());
				break;
			case GETCACHEDATA_SUCCESS:  //发送下载，取出要下载的链接和总的大小
				BookBean bookBean = (BookBean) msg.obj;
				if (bookBean == null) {
					clearDwonloadingBookId();
					break;
				}
				ImageView imageView = new ImageView(context);
				ImageLoader.getInstance().displayImage(bookBean.getFaceImgPlay(), imageView);
				DownLoadBean downLoadBean = new DownLoadBean();
				int hasDownLoad = 0 ;
				ArrayList<String> urlList = new ArrayList<String>(); 
				List<SelectionVo> selectionVos = bookBean.getSectionList();
				if (selectionVos != null && selectionVos.size() > 0) {
					for (SelectionVo selectionVo : selectionVos) {
						if (bookBean.getProSize() > 0) {
							if (checkDownLoadStatus(selectionVo.getProAudioUrl(), selectionVo.getProSize(),selectionVo.getBookId())) {
								urlList.add(selectionVo.getProAudioUrl());
							} else {
								hasDownLoad += selectionVo.getProSize();
							}
						}
						if (bookBean.getDoubiSize() > 0) {
							if (checkDownLoadStatus(selectionVo.getDoubiAudioUrl(), selectionVo.getDoubiSize(),selectionVo.getBookId())) {
								urlList.add(selectionVo.getDoubiAudioUrl());
							} else {
								hasDownLoad += selectionVo.getDoubiSize();
							}
						}
						if (bookBean.getEnSize() > 0) {
							if (checkDownLoadStatus(selectionVo.getEnAudioUrl(), selectionVo.getEnSize(),selectionVo.getBookId())) {
								urlList.add(selectionVo.getEnAudioUrl());
							}else {
								hasDownLoad += selectionVo.getEnSize();
							}
						}
					}
				}
				if (urlList != null && urlList.size() > 0) {
					Log.d("urlList", "ADD urlList");
					downLoadBean.setHasDownLoadSize(hasDownLoad);
					downLoadBean.setBookId(bookBean != null ? bookBean.getBookId() : 0);
					downLoadBean.setTotalSize(bookBean != null ? bookBean.getProSize() + bookBean.getDoubiSize() + bookBean.getEnSize() : 0);
					downLoadBean.setUrlList(urlList);
					EventBus.getEventBus("list_download").post(downLoadBean);
				} else {
					downloadingBookId = 0;
					next();
				}
				break;
			case 100:
				List<AnchorBean> list = (List<AnchorBean>) msg.obj;
				if (list != null  && list.size() > 0) {
					for (AnchorBean anchorBean : list) {
						ImageView view = new ImageView(context);
						ImageLoader.getInstance().displayImage(anchorBean.getFace(), view);
					}
				}
				break;
			}
		};
	};
	
	
	public void addDownloadBookId(int bookId){
		if (!bookIds.contains(bookId) && bookId != downloadingBookId) {
			if (bookIds.size() > 0 || (bookIds.size() == 0 && downloadingBookId > 0)) {
				needPrepare = false;
			}else {
				needPrepare = true;
			}
			ProgressEvent event = new ProgressEvent();
			event.setCurrentRatio(0);
			event.setBookId(bookId);
			EventBus.getEventBus("downloadProgress").post(event);
			bookIds.add(bookId);
		}
	}
	
	public void clearDwonloadingBookId(){
		downloadingBookId = 0;
	}

	public DownLoadManager3 setNeedDownLoadBookId(int downLoadBookId) {
		addDownloadBookId(downLoadBookId);
		return this;
	}
	
	public DownLoadManager3(Context context){
		this.context = context;
	}
	
	private static DownLoadManager3 downLoadManager;
	
	public static DownLoadManager3 getInstance(Context context){
		if (downLoadManager == null) {
			downLoadManager = new DownLoadManager3(context);
		}
		return downLoadManager;
	}
	
	
	/**
	 * 下载下一个
	 */
	public void next(){
		if (bookIds != null && bookIds.size() > 0) {
			needPrepare = true;
			prepare();
		}
	}
	
	/**
	 * 检查本地是否下载
	 * @param url
	 * @param urlLength
	 */
	public boolean checkDownLoadStatus(String url, int urlLength,int bookId){
		boolean flag = true;
		if (!TextUtils.isEmpty(url)) {
			String fileName = CommonMethod.getFileName(url);
			File file = new File(FileUtil.getFileCachePath() + DownLoadInfo.DOWNLOAD +"/" + bookId +"/" + fileName);
			if (file.exists()) {
				if (file.length() == urlLength) {
					flag = false;
				} else {
					file.delete();
				}
			}
		}
		return flag;
	}

	/**
	 * 确定下载完成后要保存的数据，先读取本地，要是本地没有，则从网络获取数据
	 */
	public void prepare() {
		if (needPrepare) {
			Pool.getPool().execute(new Runnable() {
				@Override
				public void run() {
					synchronized (this) {
						ResponeResult responeResult = new ResponeResult();
						try {
							int bookId = 0;
							if (bookIds != null && bookIds.size() > 0) {
								bookId = bookIds.remove(0);
								downloadingBookId = bookId;
							}
							
							if (bookId != 0 && HttpRequestHelper.getAnchorList(context, bookId, handler)) {
								BookBean bookBean = StaticReference.mutilDBSupport.getDao(BookBean.class).queryForId(bookId);
								if (bookBean == null || (bookBean != null && (isEmpty(bookBean.getAbout()) || isEmpty(bookBean.getGoldWord())))) {
									//请求
									List<NameValuePair> params = new ArrayList<NameValuePair>();
									params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(context, HttpRequestHelper.USERID, 0))));
									params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, String.valueOf(bookId)));
										
									HttpEntity entity = HttpHelper.getInfoByPost(HttpRequestHelper.READ_MODE, params, context);
									String _result = HttpHelper.entity2String(entity);
									JSONObject jsonResult = new JSONObject(_result);
									JSONObject result = jsonResult.getJSONObject(HttpCommonInfo.RESULT);
									int code = result.getInt(HttpCommonInfo.RESULT_CODE);
									String msg = result.getString(HttpCommonInfo.RESULT_MSG);
									responeResult.setCode(code);
									responeResult.setMsg(msg);
									if (code == 0) {
										responeResult.setData(jsonResult.getString(HttpCommonInfo.DATA));
										handler.obtainMessage(HttpRequestHelper.GETDATA_SUCCESS, responeResult).sendToTarget();
									} else {
										handler.sendEmptyMessage(-100);
									}
								} else {
									List<SelectionVo> selectionVos = StaticReference.mutilDBSupport.getDao(SelectionVo.class).queryForEq("bookId", bookId);
									bookBean.setSectionList(selectionVos);
									handler.obtainMessage(GETCACHEDATA_SUCCESS,bookBean).sendToTarget();
								}
						 } else {
							 responeResult = null;
						 }
						} catch (SQLException e) {
							e.printStackTrace();
							responeResult = null;
						} catch (ClientProtocolException e) {
							e.printStackTrace();
							responeResult = null;
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
							responeResult = null;
						} catch (IOException e) {
							e.printStackTrace();
							responeResult = null;
						} catch (JSONException e) {
							e.printStackTrace();
							responeResult = null;
						} finally{
							if (responeResult == null) {
								downloadingBookId = 0;
								next();
							}
						}
					}
				}
			});
		}
	}
	
	private void getLocalBookBean(final int bookId){
		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				try {
					BookBean bookBean = StaticReference.mutilDBSupport.getDao(BookBean.class).queryForId(bookId);
					List<SelectionVo> selectionVos = StaticReference.mutilDBSupport.getDao(SelectionVo.class).queryForEq("bookId", bookId);
					if (bookBean != null && selectionVos != null ) {
						bookBean.setSectionList(selectionVos);	
					}
					handler.obtainMessage(GETCACHEDATA_SUCCESS,bookBean).sendToTarget();
				} catch (SQLException e) {
					e.printStackTrace();
				}				
			}
		});
	}
	
	boolean isEmpty(String txt){
		return TextUtils.isEmpty(txt);
	}

	@Override
	public void okButtonClick(Dialog dialog) {
		dialog.dismiss();
		prepare();
	}

	@Override
	public void cancelButtonClick(Dialog dialog) {
		dialog.dismiss();
	}

	@Override
	public void otherButtonClick(Dialog dialog) {
		dialog.dismiss();
	}
	
	public void showDialog(int needDownloadSize){
		CommonAlertDialog alertDialog = new CommonAlertDialog(context);
		alertDialog.setTextMessage(String.format(context.getResources().getString(R.string.download_notice), CommonMethod.calculationNum(needDownloadSize)));
		alertDialog.setShowTitle(true);
		String[] a = {context.getResources().getString(R.string.app_continue),context.getResources().getString(R.string.app_cancel)};
		alertDialog.setBtns(this,a);
		alertDialog.show();
	}
	
	/**
	 * 一个下载项目
	 * @param needDownloadSize
	 */
	public void prepareBefore(int needDownloadSize){
		if (!(boolean)SharedPreferencesUtils.getParam(context, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)) {
			switch (CommonMethod.getNetworkState(context)) {
			case 0:
				CommonMethod.makeNotice(context, context.getResources().getString(R.string.connect_err_io));
				break;
			case 1:
				prepare();
				break;
			case 2:
				showDialog(needDownloadSize);
				break;
			}
		}else {
			prepare();
		}
	}
	
	/**
	 * 批量下载
	 * @param allSize
	 * @param bookIds
	 */
	public void prepareBefore(int allSize , final ArrayList<Integer> bookIds){
		switch (CommonMethod.getNetworkState(context)) {
		case 0:
			CommonMethod.makeNotice(context, context.getResources().getString(R.string.connect_err_io));
			break;
		case 1:
			downLoadAll(bookIds);
			break;
		case 2:
			CommonAlertDialog alertDialog = new CommonAlertDialog(context);
			alertDialog.setTextMessage(String.format(context.getResources().getString(R.string.download_notice), CommonMethod.calculationNum(allSize)));
			alertDialog.setShowTitle(true);
			String[] a = {context.getResources().getString(R.string.app_continue),context.getResources().getString(R.string.app_cancel)};
			alertDialog.setBtns(new DialogListener() {
				
				@Override
				public void otherButtonClick(Dialog dialog) {
					dialog.dismiss();
				}
				
				@Override
				public void okButtonClick(Dialog dialog) {
					downLoadAll(bookIds);
					dialog.dismiss();
				}
				
				@Override
				public void cancelButtonClick(Dialog dialog) {
					dialog.dismiss();
				}
			},a);
			alertDialog.show();
			break;
		}
	}
	
	public void downLoadAll(ArrayList<Integer> bookIds){
		for (int i = 0; i < bookIds.size(); i++) {
			setNeedDownLoadBookId(bookIds.get(i)).prepare();
		}
	}
	
}
